#
# @lc app=leetcode.cn id=99 lang=python3
#
# [99] 恢复二叉搜索树
#

# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

class Solution:
    def recoverTree(self, root: TreeNode) -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        s = t = None
        prev = TreeNode(float('-inf'))

        def traverse(root: TreeNode):
            nonlocal prev, s, t
            if not root:
                return

            traverse(root.left)
            
            if root.val < prev.val:
                s = prev if s is None else s
                t = root
            prev = root

            traverse(root.right)

        traverse(root)
        s.val, t.val = t.val, s.val
# @lc code=end
